package com.hucsmn.stumansys.service.impl;

import com.hucsmn.stumansys.dao.StudentDao;
import com.hucsmn.stumansys.entity.Student;
import com.hucsmn.stumansys.service.StudentService;
import com.hucsmn.stumansys.utils.ConvertUtils;

import java.util.List;

/**
 * StudentService 业务逻辑的实现类。
 * @author hucsmn
 */
public class StudentServiceImpl implements StudentService {
    private final StudentDao studentDao = StudentDao.getInstance();

    @Override
    public boolean add(Student student) {
        if (!ConvertUtils.validateStudent(student)) {
            return false;
        }
        return studentDao.addStudent(student);
    }

    @Override
    public boolean remove(int id) {
        return studentDao.removeStudent(id);
    }

    @Override
    public boolean remove(int... ids) {
        if (ids == null || ids.length == 0) {
            return true;
        }
        if (ids.length == 1) {
            return studentDao.removeStudent(ids[0]);
        }
        return studentDao.removeStudents(ids);
    }

    @Override
    public boolean modify(Student student) {
        if (!ConvertUtils.validateStudent(student)) {
            return false;
        }
        return studentDao.setStudent(student);
    }

    @Override
    public Student findById(int id) {
        return studentDao.getStudentById(id);
    }

    @Override
    public Student findByCard(String card) {
        if (card == null) {
            return null;
        }
        return studentDao.getStudentByCard(card);
    }

    @Override
    public long count(String contains) {
        if (contains == null || contains.isEmpty()) {
            return studentDao.countStudents();
        }
        return studentDao.countStudentsNameContains(contains);
    }

    @Override
    public List<Student> list(String contains, int page, int limit) {
        limit = Integer.max(limit, 1);
        int pageMax = (int) Long.min(
                Long.MAX_VALUE % limit == 0 ? Long.MAX_VALUE / limit : Long.MAX_VALUE / limit + 1,
                Integer.MAX_VALUE);
        page = Integer.min(Integer.max(page, 1), pageMax);
        long since = Long.max((page - 1) * (long) limit, 0);

        if (contains == null || contains.isEmpty()) {
            return studentDao.getStudents(since, limit);
        }
        return studentDao.getStudentsNameContains(contains, since, limit);
    }
}
